package com.qqtech.qquan.user.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.community.model.CommunityAddr;
import com.qqtech.qquan.community.model.CommunityAddrVo;
import com.qqtech.qquan.community.model.CommunityBase;
import com.qqtech.qquan.community.service.CommunityAddrService;
import com.qqtech.qquan.community.service.CommunityBaseService;
import com.qqtech.qquan.sys.model.SysArea;
import com.qqtech.qquan.sys.model.SysAreaQuery;
import com.qqtech.qquan.sys.model.SysAreaVo;
import com.qqtech.qquan.sys.service.SysAreaService;
import com.qqtech.qquan.user.model.UserAddress;
import com.qqtech.qquan.user.model.UserAddressQuery;
import com.qqtech.qquan.user.model.UserAddressVo;
import com.qqtech.qquan.user.model.UserLoginVo;
import com.qqtech.qquan.user.service.UserAddressService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/user/address")
public class UserAddressController extends BaseWebController<UserAddress, UserAddressQuery> {
	@Resource
	private UserAddressService userAddressService;

	@Resource
	private SysAreaService sysAreaService;
	@Resource
	private CommunityBaseService communityBaseService;
	@Resource
	private CommunityAddrService communityAddrService;

	@Override
	protected BaseService<UserAddress> getBaseService() {
		return userAddressService;
	}

	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/page")
	@ResponseBody
	public Result page(@RequestBody UserAddressQuery userAddressQuery) {
		Result result = new Result();
		if (userAddressQuery == null) {
			userAddressQuery = new UserAddressQuery();
		}
		UserLoginVo userLoginVo = super.getLoginUser();
		Integer userId = userLoginVo.getId();
		userAddressQuery.setCreatorId(userId);
		userAddressQuery.setStatus(YesNoEnum.YES.getCode());
		Pageable pageKit = new PageKit(userAddressQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<UserAddressVo> page = userAddressService.queryPageList(userAddressQuery, pageKit);
		result.put("page", page);
		return result;
	}

	/**
	 * 获取默认地址
	 * 
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/getDefault")
	@ResponseBody
	public Result getDefault() {
		UserAddress userAddressQuery = new UserAddress();
		UserLoginVo userLoginVo = super.getLoginUser();
		Integer userId = userLoginVo.getId();
		Result result = new Result();
		userAddressQuery.setIsDefault(1);
		userAddressQuery.setCreatorId(userId);
		userAddressQuery.setStatus(1);
		//UserAddress userAddress = userAddressService.getOne(userAddressQuery, new PageOrder(Direction.DESC, "id"));
		Pageable pageKit = new PageKit(userAddressQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		List<UserAddress> userAddressList =  userAddressService.queryList(userAddressQuery, pageKit);
		if(userAddressList != null && userAddressList.size() > 0){
			result.put("userAddress", userAddressList.get(0));
		}
		//result.put("userAddress", userAddress);
		return result;
	}

	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/add")
	@ResponseBody
	public Result add(@RequestBody UserAddressVo vo) {
		Result result = new Result();
		CommunityBase communityBase = null;
		CommunityAddr communityAddr = null;
		if (vo == null) {
			result.addErr("参数不能为空");
		} else {
			if (StringUtil.isBlank(vo.getContactName())) {
				result.addErr("收货人姓名不能为空");
			}else if (vo.getContactName().length() > 10){
				result.addErr("姓名不能超过10个字符");
			} 
			if (StringUtil.isBlank(vo.getContactPhone())) {
				result.addErr("收货人手机号不能为空");
			} else if (!StringUtil.isPhone(vo.getContactPhone())) {
				result.addErr("无效的手机号");
			}
			if (vo.getCommunityId() == null) {
				result.addErr("请选择社区");
			} else {
				communityBase = communityBaseService.getById(vo.getCommunityId());
				if (communityBase == null) {
					result.addErr("社区不存在");
				} else {
					if (vo.getCommunityAddrId() == null) {
						result.addErr("请选择社区层级");
					} else {
						communityAddr = communityAddrService.getById(vo.getCommunityAddrId());
						if (communityAddr == null) {
							result.addErr("社区层级不存在");
						} else {
							List<CommunityAddrVo> list = communityAddrService.queryListByParentId(vo.getCommunityId(),communityAddr.getId());
							if (list != null && !list.isEmpty()) {
								result.addErr("社区层级没有选完");
							}
						}
					}
				}
			}
			if (StringUtil.isBlank(vo.getHouseNumber())) {
				result.addErr("请填写门牌号");
			} else if (vo.getHouseNumber().length() > 10) {
				result.addErr("门牌号不能超过10个字符");
			}
		}
		if (result.checkForm()) {
			UserAddress entity = new UserAddress();
			entity.setCreatorId(super.getUserId());
			entity.setIsDefault(2);
			entity.setNewAt(TimeUtil.now());
			entity.setContactName(vo.getContactName().trim());
			entity.setContactPhone(vo.getContactPhone());
			entity.setCommunityId(vo.getCommunityId());
			entity.setX(communityBase.getX());
			entity.setY(communityBase.getY());
			SysArea city = sysAreaService.getById(communityBase.getCityId());
			SysArea province = sysAreaService.getById(city.getParentId());
			SysArea region = sysAreaService.getById(communityBase.getDistrictId());
			entity.setProvinceId(province.getId());
			entity.setProvinceName(province.getName());
			entity.setCityId(city.getId());
			entity.setCityName(city.getName());
			entity.setRegionId(region.getId());
			entity.setRegionName(region.getName());
			entity.setHouseNumber(vo.getHouseNumber().trim());
			entity.setNextAddr("");
			List<CommunityAddrVo> pCommunityAddr = communityAddrService.queryListByChildren(vo.getCommunityAddrId(), vo.getCommunityId());
			for (CommunityAddrVo t : pCommunityAddr) {
				entity.setNextAddr(t.getName().trim()+entity.getNextAddr());
			}
			entity.setNextAddr(communityBase.getName() + entity.getNextAddr());
			int id = userAddressService.addUserAddress(entity);
			result.put("id", id);
		}
		return result;
	}

	/**
	 * 设置默认地址
	 * 
	 * @param userAddress
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/setDefault")
	@ResponseBody
	public Result setDefault(@RequestBody UserAddress userAddress) {
		Integer userId = getUserId();
		Result result = new Result();
		userAddress = userAddressService.getById(userAddress.getId());
		if (userAddress == null) {
			result.addErr("数据不存在");
		} else if (userAddress.getCreatorId().intValue() != userId) {
			result.addErr("不能修改他人数据");
		}
		if (result.checkForm()) {
			userAddressService.handleDefaultAddress(userAddress.getId());
		}
		return result;
	}

	@RequestMapping(value = "/detail")
	@ResponseBody
	public Result detail(@RequestBody UserAddressQuery userAddressQuery) {
		Result result = new Result();
		UserAddressVo userAddress = userAddressService.getById(userAddressQuery.getId());
		if (StringUtil.isBlank(userAddress.getNextAddr()) && userAddress.getCommunityId() != null) {
			CommunityBase communityBase = communityBaseService.getById(userAddress.getCommunityId());
			if (communityBase != null) {
				userAddress.setNextAddr(communityBase.getName());
			}
		}
		result.put("userAddress", userAddress);
		return result;
	}

	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/edit")
	@ResponseBody
	public Result edit(@RequestBody UserAddressVo vo) {
		Result result = new Result();
		CommunityBase communityBase = null;
		CommunityAddr communityAddr = null;
		if (vo == null) {
			result.addErr("参数不能为空");
		} else if (vo.getId() == null) {
			result.addErr("参数id不能为空");
		} else if (!checkCanEdit(vo.getId(),super.getUserId())) {
			result.addErr("不是你的数据");
		} else {
			if (StringUtil.isBlank(vo.getContactName())) {
				result.addErr("收货人姓名不能为空");
			}else if (vo.getContactName().length() > 10){
				result.addErr("姓名不能超过10个字符");
			} 
			if (StringUtil.isBlank(vo.getContactPhone())) {
				result.addErr("收货人手机号不能为空");
			} else if (!StringUtil.isPhone(vo.getContactPhone())) {
				result.addErr("无效的手机号");
			}
			if (vo.getCommunityId() != null) {
				communityBase = communityBaseService.getById(vo.getCommunityId());
				if (communityBase == null) {
					result.addErr("社区不存在");
				} else {
					if (vo.getCommunityAddrId() == null) {
						result.addErr("请选择社区层级");
					} else {
						communityAddr = communityAddrService.getById(vo.getCommunityAddrId());
						if (communityAddr == null) {
							result.addErr("社区层级不存在");
						} else {
							List<CommunityAddrVo> list = communityAddrService.queryListByParentId(vo.getCommunityId(),communityAddr.getId());
							if (list != null && !list.isEmpty()) {
								result.addErr("社区层级没有选完");
							}
						}
					}
				}
			}
			if (StringUtil.isBlank(vo.getHouseNumber())) {
				result.addErr("请填写门牌号");
			} else if (vo.getHouseNumber().length() > 10) {
				result.addErr("门牌号不能超过10个字符");
			}
		}
		if (result.checkForm()) {
			UserAddress entity = new UserAddress();
			entity.setId(vo.getId());
			entity.setContactName(vo.getContactName().trim());
			entity.setContactPhone(vo.getContactPhone());
			if (communityBase != null) {
				entity.setCommunityId(vo.getCommunityId());
				entity.setX(communityBase.getX());
				entity.setY(communityBase.getY());
				SysArea city = sysAreaService.getById(communityBase.getCityId());
				SysArea province = sysAreaService.getById(city.getParentId());
				SysArea region = sysAreaService.getById(communityBase.getDistrictId());
				entity.setProvinceId(province.getId());
				entity.setProvinceName(province.getName());
				entity.setCityId(city.getId());
				entity.setCityName(city.getName());
				entity.setRegionId(region.getId());
				entity.setRegionName(region.getName());
				entity.setNextAddr("");
				List<CommunityAddrVo> pCommunityAddr = communityAddrService.queryListByChildren(vo.getCommunityAddrId(), vo.getCommunityId());
				for (CommunityAddrVo t : pCommunityAddr) {
					entity.setNextAddr(t.getName().trim()+entity.getNextAddr());
				}
				entity.setNextAddr(communityBase.getName() + entity.getNextAddr());
			}
			entity.setHouseNumber(vo.getHouseNumber().trim());
			entity.setUpdAt(TimeUtil.now());
			userAddressService.updateById(entity);
			result.put("userAddress", vo);
		}
		return result;
	}

	public boolean checkCanEdit(Integer userAddressId, Integer userId) {
		UserAddress userAddress = userAddressService.getById(userAddressId);
		return userAddress.getCreatorId().intValue() == userId;
	}

	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/remove")
	@ResponseBody
	public Result remove(@RequestBody UserAddress userAddress) {
		Integer userId = getUserId();
		Result result = new Result();
		userAddress = userAddressService.getById(userAddress.getId());
		if (userAddress == null) {
			result.addErr("数据不存在");
		} else if (userAddress.getCreatorId().intValue() != userId) {
			result.addErr("不能修改他人数据");
		}
		if (result.checkForm()) {
			UserAddress update = new UserAddress();
			update.setId(userAddress.getId());
			update.setCreatorId(userId);
			update.setStatus(YesNoEnum.NO.getCode());
			update.setUpdAt(TimeUtil.now());
			userAddressService.removeUserAddress(update);
		}
		return result;
	}
}
